package ac.svn.accesscontrol.store;

import java.util.HashSet;
import java.util.Set;

import javax.swing.JLabel;

import ac.svn.accesscontrol.ui.UIComponentLibrary;

public class ParsedItem 
{
	private String lhsEntity;
	private Set<String> rhsEntities;
	private String sourceString;
	private boolean valid = true;
	private static JLabel errorLabel = null;;
	public ParsedItem(String srcString)
	{
		this.sourceString = srcString; 
		lhsEntity = "";
		rhsEntities = new HashSet<String>();
		if(null == errorLabel)
		{
			errorLabel = (JLabel) UIComponentLibrary.getComponent("C_ERROR_LABEL");
		}
		parseString();
	}

	private void parseString() {
		if(sourceString.contains("=") && (1 == countOccurences("=")))
		{
			String[] split = sourceString.split("=");
			String rhsString = "";
			try
			{
				if(null != split && 0 != split.length)
				{
					lhsEntity = split[0];
					if(1 == split.length)
					{
						rhsString = "";
					}
					else
					{
						rhsString = split[1];
					}
				}

				String[] rhsSplit = rhsString.split(",");
				if(null != rhsSplit)
				{
					for(int nIndex = 0 ; nIndex < rhsSplit.length;nIndex++)
					{
						String item = rhsSplit[nIndex];
						rhsEntities.add(item.trim());
					}
				}
			}
			catch(Exception e)
			{
				valid = false;
			}
			//errorLabel.setText(""");
		}
		else
		{
			errorLabel.setText("Error found at line: " + sourceString + "  Assignment is invalid.");
		}
	}

	public String getLhsEntity() {
		return lhsEntity;
	}

	public void setLhsEntity(String lhsEntity) {
		this.lhsEntity = lhsEntity;
	}

	public Set<String> getRhsEntities() {
		return rhsEntities;
	}

	public void setRhsEntities(Set<String> rhsEntities) {
		this.rhsEntities = rhsEntities;
	}

	public String getSourceString() {
		return sourceString;
	}

	public void setSourceString(String sourceString) {
		this.sourceString = sourceString;
	}

	public boolean isValid() {
		return valid;
	}

	private int countOccurences(String findStr)
	{
		String temp = new String(sourceString);
		int charCount = sourceString.length() - temp.replaceAll(findStr, "").length();
		return charCount;
	}
}


